﻿using AspNetMVCTodo.Data;
using AspNetMVCTodo.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace AspNetMVCTodo.Services
{
    public class TodoItemService : ITodoItemService
    {
        private readonly ApplicationDbContext _context;

        public TodoItemService(ApplicationDbContext context)
        {
            _context = context;
        }

        public Task<TodoItem[]> GetIncompleteItemsAsync(ApplicationUser user)
        {
            var items = _context.Items.Where(x => !x.IsDone && x.UserId == user.Id).ToArrayAsync();
            //var item = _context.Items.FirstOrDefault();
            return items;
        }

        public async Task<bool> AddItemAsync(TodoItem newItem, ApplicationUser user)
        {
            newItem.Id = Guid.NewGuid();
            newItem.IsDone = false;
            newItem.DueAt = newItem.DueAt ?? DateTimeOffset.Now.AddDays(3);
            newItem.UserId = user.Id;

            _context.Items.Add(newItem);

            var saveResult = await _context.SaveChangesAsync();
            return saveResult == 1;
        }

        public async Task<bool> MarkDoneAsync(Guid id, ApplicationUser user)
        {
            var item = await _context.Items.FirstOrDefaultAsync(x => x.Id == id && x.UserId == user.Id);
            if (item == null)
            {
                return false;
            }
            item.IsDone = true;
            var saveResult = await _context.SaveChangesAsync();
            return saveResult == 1;
        }
    }
}
